use std::path::Path;

use anyhow::Result;
use quick_xml::{events::Event, Reader};

#[derive(Debug, Default)]
pub struct PackageInfo {
    pub package_name: Option<String>,
    pub version_code: Option<u64>,
    pub version_name: Option<String>,
}

pub fn parse_manifest(file_path: impl AsRef<Path>) -> Result<PackageInfo> {
    let mut reader = Reader::from_file(file_path)?;
    let mut buffer = vec![];

    let mut ret = PackageInfo {
        ..Default::default()
    };

    loop {
        let event = reader.read_event_into(&mut buffer)?;
        match event {
            Event::Start(e) => match e.name().as_ref() {
                b"manifest" => {
                    for attr in e.attributes().flatten() {
                        match attr.key.as_ref() {
                            b"package" => {
                                ret.package_name =
                                    Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                            b"android:versionCode" => {
                                let s = String::from_utf8_lossy(&attr.value);
                                if let Ok(x) = s.parse::<u64>() {
                                    ret.version_code = Some(x);
                                }
                            }
                            b"android:versionName" => {
                                ret.version_name =
                                    Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                            _ => {}
                        }
                    }
                }
                b"activity" => {}
                _ => {}
            },
            Event::Eof => break,
            _ => {}
        }
        buffer.clear();
    }

    Ok(ret)
}
